package com.ProtocalAndUdp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import Event.MyEvent;
import Event.MyEventListenerInterface;
import Event.MyEventRegister;

/**
 * UDP客户端程序，用于对服务端发送数据，并接收服务端的回应信息.
 */
public class UdpClientSocket {

	private byte[] buffer = new byte[1024];
	private DatagramSocket ds = null;
	private static UdpClientSocket client = null;
	private String severIp = "192.168.1.100";
	private int serverPort = 5070;
	private int receivePort = 5071;
	private MyEventRegister register = null;
	public boolean isRun = true;

	public String getIp() {

		return severIp;
	}

	public void setIp(String ip) {

		this.severIp = ip;
	}

	public int getServerPort() {

		return serverPort;
	}

	public void setServerPort(int port) {

		this.serverPort = port;
	}

	public int getReceivePort() {

		return receivePort;
	}

	public void setReceivePort(int receivePort) {

		this.receivePort = receivePort;
	}

	/**
	 * 构造函数，创建UDP客户端
	 * 
	 * @throws Exception
	 */
	public UdpClientSocket() throws Exception {

		register = new MyEventRegister();// 事件对象

	}

	public static UdpClientSocket getClient() throws Exception {

		if (client == null) {
			client = new UdpClientSocket();
		}
		return client;
	}

	/**
	 * 向指定的服务端发送数据信息.
	 * 
	 * @param bytes
	 *            发送的数据信息
	 * @return 返回构造后俄数据报
	 * @throws IOException
	 */
	public final DatagramPacket send(
			final byte[] bytes) throws Exception {

		DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress
				.getByName(severIp), serverPort);
		ds.send(dp);
		return dp;
	}

	/**
	 * 接收从指定的服务端发回的数据.
	 * 
	 * @return 返回从指定的服务端发回的数据.
	 */
	public final void receive()
			throws Exception {

		if (ds == null)
			ds = new DatagramSocket(receivePort); // 监听本地端口

		System.out.println("start receiving data...");

		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
		while (isRun) {
			ds.receive(dp);
			String info = new String(dp.getData(), 0, dp.getLength());
			PackRezult pr = PackAnalysis.ReceiveData(info);
			// 定义并设置事件传出对象
			MyEvent evt = new MyEvent("");// 事件传出消息对象
			evt.setRezult(pr);
			// 触发接收事件
			register.fireMyEvent(evt);
			System.out.println("服务端回应数据：" + Util.getNowTime() + " " + info);
		}
	}

	public MyEventRegister getRegister() {

		return register;
	}

	public void setRegister(MyEventRegister register) {

		this.register = register;
	}

	public void Close() {

		ds.close();
	}

}
